<template>
  <UploadExcel :on-success="handleSuccess" />
</template>

<script>
import { reqImportEmployee } from '@/api/employee'
export default {
  name: 'Import',

  data() {
    return {

    }
  },
  computed: {
    type() {
      return this.$route.query.type
    }
  },

  mounted() {

  },

  methods: {
    // 上传成功函数
    handleSuccess({ header, results }) {
    //   console.log(header, results)
      if (this.type === 'user') {
        this.batchUser(header, results)
      }
    },
    // 批量导入员工
    async batchUser(header, results) {
      const userRelations = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber'
      }
      const arr = []
      results.forEach(item => {
        const obj = {}
        for (const k in item) {
          const enKey = userRelations[k]
          if (['timeOfEntry', 'correctionTime'].includes(enKey)) {
            obj[enKey] = this.formatExcelDate(item[k])
          } else {
            obj[enKey] = item[k]
          }
        }
        arr.push(obj)
      })
      console.log(arr)
      //   批量添加员工
      await reqImportEmployee(arr)
      this.$message.success('批量添加员工成功')
      this.$router.back()
    },
    // 修改excel 储存时间的函数
    formatExcelDate(numb, format) {
      const time = new Date(numb * 24 * 3600000 + 1) // 毫秒
      time.setYear(time.getFullYear() - 70)
      const year = time.getFullYear() + ''
      const month = time.getMonth() + 1 + ''
      const date = time.getDate() - 1 + ''
      if (format && format.length === 1) {
        return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
      }
      return year + (month < 10 ? '0' + month : month) + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
